﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace Coldairarrow.Util
{
    /// <summary>
    /// Execl文档操作帮助类
    /// </summary>
    public class ExeclHelper
    {
        /// <summary>
        /// 将WorkSheet转换成泛型list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="worksheet"></param>
        /// <param name="headerRowIndex">标题开始的行数</param>
        /// <param name="dataRowIndex">数据开始的行数</param>
        /// <returns></returns>

        public static List<T> WorkSheetToList<T>(ExcelWorksheet worksheet, int headerRowIndex, int dataRowIndex) where T : new()
        {
            var list = new List<T>();
            var properties = typeof(T).GetProperties();
            // 建立列名到属性的映射
            var columnMappings = new Dictionary<string, PropertyInfo>();
            foreach (var prop in properties)
            {
                var attr = prop.GetCustomAttribute<Coldairarrow.Util.ExcelColumn>();
                if (attr != null)
                {
                    columnMappings[attr.ColumnName] = prop;
                }
                else
                {
                    // 如果没有特性，默认使用属性名
                    columnMappings[prop.Name] = prop;
                }
            }

            // 获取标题行
            int colCount = worksheet.Dimension.Columns;

            // 建立列索引到属性的映射
            var indexToProperty = new Dictionary<int, PropertyInfo>();
            for (int col = 1; col <= colCount; col++)
            {
                string columnName = worksheet.Cells[headerRowIndex, col].Value?.ToString();
                if (columnName != null && columnMappings.TryGetValue(columnName, out var property))
                {
                    indexToProperty[col] = property;
                }
            }

            // 读取数据行
            var dataRow = dataRowIndex.IsNullOrEmpty() || dataRowIndex == 0 ? headerRowIndex + 1 : dataRowIndex;
            for (int row = dataRow ; row <= worksheet.Dimension.Rows; row++)
            {
                var item = new T();

                foreach (var mapping in indexToProperty)
                {
                    int col = mapping.Key;
                    var property = mapping.Value;
                    var cellValue = worksheet.Cells[row, col].Value;

                    if (cellValue != null)
                    {
                        try
                        {
                            object convertedValue = Convert.ChangeType(cellValue, property.PropertyType);
                            property.SetValue(item, convertedValue);
                        }
                        catch
                        {
                            // 处理转换失败
                        }
                    }
                }

                list.Add(item);
            }

            return list;
        }
    }
}
